package com.sctvcloud.qingchuan.ui.activities;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Pair;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.gridsum.videotracker.entity.VideoInfo;
import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.ruihang.generalibrary.utils.ListUtils;
import com.sctvcloud.qingchuan.R;
import com.sctvcloud.qingchuan.application.Constances;
import com.sctvcloud.qingchuan.base.BaseAccountActivity;
import com.sctvcloud.qingchuan.beans.AccountBean;
import com.sctvcloud.qingchuan.beans.AccountCommentBean;
import com.sctvcloud.qingchuan.beans.AccountDoUpBean;
import com.sctvcloud.qingchuan.beans.AccountNewsArticleBean;
import com.sctvcloud.qingchuan.beans.AccountNewsDetail;
import com.sctvcloud.qingchuan.beans.AttitudesBean;
import com.sctvcloud.qingchuan.beans.FUsers;
import com.sctvcloud.qingchuan.beans.NewsVideoBean;
import com.sctvcloud.qingchuan.beans.NewsVideoVo;
import com.sctvcloud.qingchuan.http.AbsNetCallBack;
import com.sctvcloud.qingchuan.http.NetUtils;
import com.sctvcloud.qingchuan.http.ParamsEditor;
import com.sctvcloud.qingchuan.ui.dialog.ShareFragment;
import com.sctvcloud.qingchuan.ui.utils.DataUtils;
import com.sctvcloud.qingchuan.ui.utils.GlideCircleTransform;
import com.sctvcloud.qingchuan.ui.utils.GlideUtil;
import com.sctvcloud.qingchuan.ui.utils.OnFullClick;
import com.sctvcloud.qingchuan.ui.widget.BasePlayerView;
import com.sctvcloud.qingchuan.utils.UserManager;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.RequestBody;

/**
 * 公众号 视频详情
 */
public class AccountVideoDetailActivity extends BaseAccountActivity implements BaseAccountActivity.OnAddCommentListener {
    @BindView(R.id.account_news_title)
    protected CustomFontTextView accountNewsTitle;
    @BindView(R.id.account_layout)
    protected RelativeLayout account_layout;
    @BindView(R.id.account_avatar)
    protected ImageView accountAvatar;
    @BindView(R.id.account_name)
    protected CustomFontTextView accountName;
    @BindView(R.id.account_time)
    protected CustomFontTextView accountTime;
    @BindView(R.id.account_subscribe)
    protected ImageView accountSubscribe;
    @BindView(R.id.video_player)
    protected BasePlayerView videoPlayer;
    @BindView(R.id.comment_layout_number)
    protected CustomFontTextView comment_number;
    @BindView(R.id.comment_layout_doup)
    protected CustomFontTextView comment_doup;
    public static final String NEWS_ID = "news_id";
    public static final int ADD_COMMENT = 1;
    private long newsId;
    private Handler handler;
    private AccountNewsDetail newsDetail;
    private AccountBean mAccountDetailBean;
    private AccountDoUpBean mDoUpBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        handler = new Handler();
        newsId = getIntent().getLongExtra(NEWS_ID, 0);
        getDetailData();
    }

    @Override
    protected void initInject() {
        setContentView(R.layout.activity_account_video_detail);
        ButterKnife.bind(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (null != videoPlayer) {
            videoPlayer.onPrepared();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (null != videoPlayer) {
            videoPlayer.onVideoPause();
        }
    }

    private void initPlayer(NewsVideoVo video) {
        VideoInfo videoInfo = new VideoInfo("");
        videoInfo.Cdn = "cdn";
        videoInfo.VideoOriginalName = video.getTitle();
        videoInfo.VideoName = video.getTitle();
        videoInfo.VideoUrl = video.getFormats().get(0).getUrl();
        videoInfo.extendProperty1 = "掌上青川APP_Android";
        try {
            videoInfo.extendProperty1 = "掌上青川APP_Android_" + getApplicationContext().getPackageManager().getPackageInfo(this.getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        videoInfo.extendProperty1 = NetUtils.GetNetName(this);
        videoInfo.setVideoWebChannel("///");
        initVideoPlayer(videoPlayer, videoInfo, false);
        videoPlayer.setFullClick(new OnFullClick() {
            @Override
            public void onFullClick(StandardGSYVideoPlayer player, boolean isLandscape) {
                JLog.e("vvav  full click isLandScape=" + isLandscape + "   player=" + player);
                onFullClicked(player, isLandscape);
            }
        });
        videoPlayer.setOnPlayerStatusListener(new BasePlayerView.OnPlayerStatusChanged() {
            @Override
            public void OnPlaying() {

            }

            @Override
            public void OnError() {

            }

            @Override
            public void OnStop() {

            }

            @Override
            public void OnEnd() {

            }
        });

    }


    private void getDetailData() {
        newsId = getIntent().getLongExtra(NEWS_ID, 0);
        if (newsId > 0) {
            String accountToken = "";
            if (null != UserManager.getInstance().getUser() && null != UserManager.getInstance().getUser().getAccountUser()) {
                accountToken = UserManager.getInstance().getUser().getAccountUser().getAccess_token();
            }
            Map<String, String> formMaildata = new HashMap<>();
            formMaildata.put("articleId", "" + newsId);
            Map<String, RequestBody> bodyMap = DataUtils.generateRequestBody(formMaildata);
            showProgress("正在加载...");
            NetUtils.getNetAdapter().getNewsItemString(getOwnerName(), accountToken, bodyMap, new AbsNetCallBack<String>(String.class) {
                @Override
                public void onSucStr(String news) {
                    if (!TextUtils.isEmpty(news)) {
                        try {
                            newsDetail = gson.fromJson(news, AccountNewsDetail.class);
                            if (newsDetail != null) {
                                initDetailData(newsDetail);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        onError(null, "数据异常");
                    }
                }

                @Override
                public void onError(Throwable ex, String errorMsg) {
                    toast(errorMsg);
                }

                @Override
                public void onEnd() {
                    closeProgress();
                }
            });

        }
    }

    /**
     * 请求公众号详情数据
     */
    private void getAccountDetail(String accointId) {
        String accessToken = "";
        if (null != UserManager.getInstance().getUser() && null != UserManager.getInstance().getUser().getAccountUser()) {
            accessToken = UserManager.getInstance().getUser().getAccountUser().getAccess_token();
        }
        Map<String, String> formMaildata = new HashMap<>();
        formMaildata.put("tenantId", Constances.TENANT_ID);
        formMaildata.put("hisUserId", accointId);

        Map<String, RequestBody> bodyMap = DataUtils.generateRequestBody(formMaildata);
        showProgress("正在加载...");
        NetUtils.getNetAdapter().getAccountInfoString(getOwnerName(), accessToken, bodyMap, new AbsNetCallBack<String>(String.class) {
            @Override
            public void onSucStr(String news) {
                if (!TextUtils.isEmpty(news)) {
                    try {
                        mAccountDetailBean = gson.fromJson(news, AccountBean.class);
                        if (mAccountDetailBean != null) {
                            initAuthorData(mAccountDetailBean);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    onError(null, "数据异常");
                }
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                toast(errorMsg);
            }

            @Override
            public void onEnd() {
                closeProgress();
            }
        });


    }

    private void initDetailData(AccountNewsDetail bean) {
        AccountNewsArticleBean article = bean.getArticle();
        if (null != article) {
            getAccountDetail(bean.getArticle().getAuthorId());
            account_layout.setVisibility(View.VISIBLE);
            accountNewsTitle.setText(article.getTitle());
        }
        String str = getString(R.string.detail_comment_no);
        if (article.getCommentCount() > 0) {
            if (article.getCommentCount() > 99) {
                str = getString(R.string.detail_comment_counts);
            } else {
                str = getString(R.string.detail_comment_count, article.getCommentCount());
            }
        }
        comment_number.setText(str);

        if (ListUtils.isListValued(bean.getVideos())) {
            final NewsVideoVo video = bean.getVideos().get(0);
            initPlayer(video);
            if (!TextUtils.isEmpty(video.getPoster())) {
                GlideUtil.getGlideWithLarge169DefNotFit(this, video.getPoster()).into(videoPlayer.getThumbImge());
            }
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (ListUtils.isListValued(video.getFormats())) {
                        NewsVideoBean vBean = video.getFormats().get(0);
                        if (null != vBean && !TextUtils.isEmpty(vBean.getUrl())) {
                            videoPlayer.onPrepared();
                            videoPlayer.setLiving(false);
                            videoPlayer.setUp(vBean.getUrl(), true, "");
                            videoPlayer.setMute(videoPlayer.isMute());
                            videoPlayer.startPlay();
                        }
                    }
                }
            }, 80);
        }
    }

    private void initAuthorData(AccountBean bean) {
        if (null != bean) {
            GlideUtil.getDynamicGlid(this, bean.getUserImage(), true).diskCacheStrategy(DiskCacheStrategy.NONE)
                    .transform(new GlideCircleTransform(this)).into(accountAvatar);
            accountName.setText(bean.getUserNickName());
            accountTime.setVisibility(View.GONE);
//            String timeStr = DateUtils.formatDate(DateUtils.getDataDate(newsItem), "");
//            accountTime.setText(timeStr);
            if (bean.isHasAttention()) {
                accountSubscribe.setImageDrawable(getResources().getDrawable(R.mipmap.icon_subscribed));
            } else {
                accountSubscribe.setImageDrawable(getResources().getDrawable(R.mipmap.icon_subscribe));
            }
        }
    }

    @OnClick(value = {R.id.account_detail_back, R.id.account_subscribe,R.id.title_top_share})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.account_detail_back:
                onBackPressed();
                break;
            case R.id.account_subscribe:
                //TODO 关注、取消关注
                if (null != mAccountDetailBean) {
                    if (null != UserManager.getInstance().getUser() && null != UserManager.getInstance().getUser().getAccountUser()) {
                        setResult(RESULT_OK);
                        toAttentionClick(mAccountDetailBean.isHasAttention());
                    } else {
                        toLogin();
                    }
                }
                break;
            case R.id.title_top_share:
                if (!TextUtils.isEmpty(newsDetail.getPreViewPath())) {
                    showShareFragment(newsDetail, new ShareFragment.OnShareFragmentClickListener() {
                        @Override
                        public void onClick(Pair<String, String> pair) {

                        }
                    });
                } else {
                    toast(R.string.share_data_wrong);
                }


                break;
        }
    }

    /**
     * 处理 关注或取消关注
     *
     * @param isAttention
     */
    private void toAttentionClick(boolean isAttention) {
        if (isAttention) {
            toUnAttentionAccount(mAccountDetailBean.getUserId(), new OnAttentionListener() {
                @Override
                public void OnAttention(boolean isSuccess, long attentionedUserNums) {

                }

                @Override
                public void OnUnAttention(boolean isSuccess, long attentionedUserNums) {
                    mAccountDetailBean.setHasAttention(!mAccountDetailBean.isHasAttention());
                    if (mAccountDetailBean.isHasAttention()) {
                        accountSubscribe.setImageDrawable(getResources().getDrawable(R.mipmap.icon_subscribed));
                    } else {
                        accountSubscribe.setImageDrawable(getResources().getDrawable(R.mipmap.icon_subscribe));
                    }
                }
            });
        } else {
            toAttentionAccount(mAccountDetailBean.getUserId(), new OnAttentionListener() {
                @Override
                public void OnAttention(boolean isSuccess, long attentionedUserNums) {
                    mAccountDetailBean.setHasAttention(!mAccountDetailBean.isHasAttention());
                    if (mAccountDetailBean.isHasAttention()) {
                        accountSubscribe.setImageDrawable(getResources().getDrawable(R.mipmap.icon_subscribed));
                    } else {
                        accountSubscribe.setImageDrawable(getResources().getDrawable(R.mipmap.icon_subscribe));
                    }
                }

                @Override
                public void OnUnAttention(boolean isSuccess, long attentionedUserNums) {

                }
            });
        }


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == CODE_REQUEST_LOGIN) {
                if (null != newsDetail) {
                    AccountNewsArticleBean article = newsDetail.getArticle();
                    if (null != article) {
                        getAccountDetail(newsDetail.getArticle().getAuthorId());
                        setResult(RESULT_OK);
                    }
                }
            } else if (requestCode == ADD_COMMENT) {
                //TODO 新增评论，刷新评论数

            }
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
//        if (videoPlayer != null && isVideoType) {
//            videoPlayer.onConfigurationChanged(this, newConfig, null);
//        }
    }

    @OnClick({R.id.comment_layout_write_comment, R.id.comment_layout_number, R.id.comment_layout_share, R.id.comment_layout_doup})
    public void newesClick(View view) {

        switch (view.getId()) {
            case R.id.comment_layout_write_comment:
                long newsId = newsDetail.getArticle().getId();
                AccountCommentBean comment = new AccountCommentBean();
                comment.setRelaId("" + newsId);
                comment.setAddUser(UserManager.getInstance().getUser().getUserId());
                comment.setType("1");
                int flag = 1;
                showCommentDialog(comment, flag, this);  //0代表新闻评论
                break;
            case R.id.comment_layout_number:
                int commentCount = newsDetail.getArticle().getCommentCount();
                if (commentCount != 0) {
                    Intent intent = new Intent(this, AccountCommentActivity.class);
                    long detailId = newsDetail.getArticle().getId();
                    if (detailId > 0) {
                        intent.putExtra(EX_ID, detailId);
                        startActivityForResult(intent, ADD_COMMENT);
                    }
                }
                break;
            case R.id.comment_layout_doup:
                newsDoUp();
                break;
            case R.id.comment_layout_share:

//                if (!TextUtils.isEmpty(fNews.getNewsShareUrl())) {
//                    this.setNewsId(fNews.getNewsId());
//                    showShareFragment(fNews, new ShareFragment.OnShareFragmentClickListener() {
//                        @Override
//                        public void onClick(Pair<String, String> pair) {
//
//
//                        }
//                    });
//                } else {
//                    toast(R.string.share_data_wrong);
//                }
                break;
        }

    }

    /**
     * 新闻点赞
     */
    private void newsDoUp() {
        if (UserManager.isLoginS()) {
            String uId = UserManager.getInstance().getUser().getUserId();
            long relationId= newsDetail.getArticle().getId();
            String type ="1";
            int flag = 1;

            NetUtils.getNetAdapter().toGetDoUpString(getOwnerName(), uId ,relationId,type,flag, new AbsNetCallBack<String>(String.class) {
                @Override
                public void onSucStr(String doupStr) {
                    if (!TextUtils.isEmpty(doupStr)) {
                        try {
                            mDoUpBean = gson.fromJson(doupStr, AccountDoUpBean.class);
                            if (mDoUpBean != null) {
                                if (null != newsDetail.getArticle()) {
//                                    if (newsDetail.getArticle().isDigg()) {
//                                        attitudes.setDigg(!attitudes.isDigg());
//                                        attitudes.setAttitudesCount(attitudes.getAttitudesCount() - 1);
//                                    } else {
//                                        attitudes.setDigg(!attitudes.isDigg());
//                                        attitudes.setAttitudesCount(attitudes.getAttitudesCount() + 1);
//                                    }
//
//                                    if (attitudes.isDigg()) {
//                                        Drawable drawable = AccountVideoDetailActivity.this.getResources().getDrawable(R.mipmap.icon_compere_btn_press);
//                                        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
//                                        comment_doup.setDrawables(drawable, null, null, null);
//                                        comment_doup.setTextColor(AccountVideoDetailActivity.this.getResources().getColor(R.color.colorTxRedMain_));
//                                    } else {
//                                        Drawable drawable = AccountVideoDetailActivity.this.getResources().getDrawable(R.mipmap.icon_compere_btn_normal);
//                                        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
//                                        comment_doup.setDrawables(drawable, null, null, null);
//                                        comment_doup.setTextColor(AccountVideoDetailActivity.this.getResources().getColor(R.color.colorOpinionSelectNo));
//                                    }
//                                    comment_doup.setText("" + mDoUpBean.getFavorCount());
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        onError(null, "数据异常");
                    }

                }

                @Override
                public void onError(Throwable ex, String errorMsg, int netCode) {
                    super.onError(ex, errorMsg, netCode);
                }
            });

        } else {
            toLogin();
        }
    }

    /**
     * 获取新闻点赞
     */
    private void getAttitudes(final String newsId) {
        ParamsEditor pe = new ParamsEditor();
//        HashMap<String, Object> param = new HashMap<>();
        pe.put("dynamicId", newsId);
        pe.put("fType", 3);//1 主播 2报料 3新闻(短视频) 4 直播
//        pe.put("token", UserManager.getInstance().getToken());
        FUsers user = UserManager.getInstance().getUser();
        if (user != null && !TextUtils.isEmpty(user.getUserId())) {
            pe.put("userId", user.getUserId());
        } else {
            pe.put("userId", "");
        }
        NetUtils.getNetAdapter().getAttitudes(getOwnerName(), pe.getEncryptedParams(UserManager.getInstance().getToken()), new AbsNetCallBack<AttitudesBean>(AttitudesBean.class) {
            @Override
            public void onSuc(AttitudesBean attitudesBean) {
                if (null != attitudesBean) {
//                    attitudes = attitudesBean;
//                    if (attitudesBean.isDigg()) {
//                        Drawable drawable = AccountVideoDetailActivity.this.getResources().getDrawable(R.mipmap.icon_compere_btn_press);
//                        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
//                        comment_doup.setDrawables(drawable, null, null, null);
//                        comment_doup.setTextColor(AccountVideoDetailActivity.this.getResources().getColor(R.color.colorTxRedMain_));
//                    } else {
//                        Drawable drawable = AccountVideoDetailActivity.this.getResources().getDrawable(R.mipmap.icon_compere_btn_normal);
//                        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
//                        comment_doup.setDrawables(drawable, null, null, null);
//                        comment_doup.setTextColor(AccountVideoDetailActivity.this.getResources().getColor(R.color.colorOpinionSelectNo));
//                    }
//                    comment_doup.setText("" + attitudesBean.getAttitudesCount());
                }
            }

            @Override
            public void onError(Throwable ex, String errorMsg, int netCode) {
                super.onError(ex, errorMsg, netCode);
            }
        });
    }

    @Override
    public void OnAddComment(boolean isSuccess) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != videoPlayer) {
            videoPlayer.onVideoPause();
            videoPlayer = null;
        }
    }
}
